package org.iryshka.skyserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import org.iryshka.logit.ConsoleFileLogging;

public class SkyWebServer {

		public int webPort  = 8099; // CONFIG data
		public File defaultPage= new File ("C:/inetpub/wwwroot/SkyNetwork_welcome.html"); // CONFIG data
		public StringBuilder skyResponse = new StringBuilder(1000);
		public static File serverDir = new File("C:/inetpub/wwwroot"); // CONFIG data
		
		private File[] filesInDir = new File[1000]; 
		private boolean foundedInDir;
		
		public static void main (String[] args) {
			
			ConfigAnalyze confAnylize = new ConfigAnalyze();
			try {
				confAnylize.ConfigFileAnylize(args);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
			SkyWebServer skyWeb = new SkyWebServer();
			try (ServerSocket skySerwerSocket = new ServerSocket(skyWeb.webPort);) {
				
				while (true) {
					Socket clientSock = skySerwerSocket.accept();				
					ConsoleFileLogging.logIt(clientSock.getRemoteSocketAddress().toString() + " connected");
					
					InputStream clientInputStream = clientSock.getInputStream();
					OutputStream clientOutputStream = clientSock.getOutputStream();
					
					SkyRequest skyRequest = new SkyRequest(); 
					SkyResponse skyResponse = new SkyResponse(skyRequest); 
					
					// relplace this loop by parsing incoming socket data to HTTPRequest object
					BufferedReader br = new BufferedReader(new InputStreamReader(clientInputStream));
		            while(true) { //  reading request 
		            	String line = br.readLine();
		                if(line == null || line.trim().length() == 0) {
		                	break;
		                }
		                skyRequest.httpRequest = skyRequest.httpRequest.append(line + "\r\n");
		            }
		            
		            System.out.println("Received request from " + clientSock.getRemoteSocketAddress() + "\r\n" + 
		            		skyRequest.httpRequest);
		            
		        	String respStr = skyRequest.selfAnalysis(skyResponse); // 
	        		if (skyRequest.attributeGet == null){
	        			skyWeb.foundedInDir = true;
	        			clientOutputStream.write(respStr.getBytes());
	        		}
	        		
	        		else if(respStr.equals("GET") && skyRequest.attributeGet.equals("/")){
	        			skyWeb.foundedInDir = true;
	        			skyWeb.givePage(skyWeb.defaultPage,clientOutputStream,skyResponse);
	        		}
	        		
	        		else if (respStr.equals("GET")){
	        			
	        			File requestedFile = new File(skyRequest.attributeGet);
	        			
	        			//NOTE: if (requestedFile.exists())
	        			
 	        			skyWeb.filesInDir = SkyRequest.currentDir.listFiles();
	        			for(File i : skyWeb.filesInDir){
	        				if ((i.getName()).equals(requestedFile.getName())){
	        					skyWeb.foundedInDir = true;
	        					if (i.isDirectory()){
	        						clientOutputStream.write((skyResponse.formHtmlList(i)).getBytes());
	        						break;
	        					}
	        					else{
	        						skyWeb.givePage(i,clientOutputStream,skyResponse);
	        						break;
	        					}
	        				}
	        			}
	        		}
	        				
    				if(skyWeb.foundedInDir == false){
    					String tempResponse = skyResponse.buildResponseHeader("404");
    					clientOutputStream.write(tempResponse.getBytes());
    				}
    				
	        		clientOutputStream.flush();
					clientSock.close();
					
					ConsoleFileLogging.logIt(clientSock.getRemoteSocketAddress().toString() + " disconnected");
		        	}
				}catch (IOException e) {
					e.printStackTrace();
				}
			} 		
		
		private void givePage (File page, OutputStream clientOutputStream, SkyResponse skyResponse) 
				throws FileNotFoundException, IOException{
			
			String helpStr = new String(SkyRequest.currentDir + "\\" + page.getName());
			try (RandomAccessFile inRAFile = new RandomAccessFile(helpStr, "r")){
				
				skyResponse.TSpace = page.length();
				String responseHeader = skyResponse.buildResponseHeader("200");
				ConsoleFileLogging.logIt("Response header is\r\n" + responseHeader);
				clientOutputStream.write(responseHeader.getBytes());
				plainBuffReader(clientOutputStream, inRAFile);
				
			} catch (SocketException se) {
				se.printStackTrace();
			} 
		}
		
		private void plainBuffReader (OutputStream clientOut, RandomAccessFile inRAFile) throws IOException, SocketException{
			byte[] buff = new byte [5000];
			int partToWrite = 0;
			while ((partToWrite = inRAFile.read(buff, 0, 5000)) != -1){
				clientOut.write(buff, 0, partToWrite);
			}
		}
	}
